class WhiteNoiseManager {
    constructor() {
        this.noises = {
            'rain': {
                name: '雨声',
                file: 'noise/9-relaxing-rain-water-green-noise.mp3',
                audio: null,
                volume: 0.5,
                isPlaying: false
            },
            'cafe': {
                name: '咖啡厅',
                file: 'noise/cafe-noise.mp3',
                audio: null,
                volume: 0.5,
                isPlaying: false
            },
            'city': {
                name: '城市声',
                file: 'noise/city-noise.mp3',
                audio: null,
                volume: 0.5,
                isPlaying: false
            },
            'fire': {
                name: '火焰声',
                file: 'noise/fire-sound.mp3',
                audio: null,
                volume: 0.5,
                isPlaying: false
            },
            'rainy-town': {
                name: '雨中小镇',
                file: 'noise/rainy-day-in-town-with-birds-singing.mp3',
                audio: null,
                volume: 0.5,
                isPlaying: false
            },
            'traffic': {
                name: '交通声',
                file: 'noise/road-transport-noise.mp3',
                audio: null,
                volume: 0.5,
                isPlaying: false
            },
            'waves': {
                name: '海浪声',
                file: 'noise/sea-waves.mp3',
                audio: null,
                volume: 0.5,
                isPlaying: false
            }
        };
        
        this.isInBackground = false; // 新增：跟踪应用是否在后台
        this.isCleanedUp = false; // 新增：防止重复清理的标志位
        this.listenersSetup = false; // 新增：防止重复设置监听器
        
        this.initAudioElements();
        this.loadSettings();
        this.setupLifecycleListeners();
    }
    
    initAudioElements() {
        Object.keys(this.noises).forEach(key => {
            const noise = this.noises[key];
            noise.audio = new Audio(noise.file);
            noise.audio.loop = true;
            noise.audio.volume = noise.volume;
            
            // 新增：设置音频在后台继续播放
            noise.audio.preload = 'auto';
        });
    }
    
    // 新增：设置生命周期监听器
    setupLifecycleListeners() {
        // 防止重复设置监听器
        if (this.listenersSetup) {
            console.log('生命周期监听器已设置，跳过重复设置');
            return;
        }
        this.listenersSetup = true;
        
        // 监听Electron主进程发送的事件
        if (typeof require !== 'undefined') {
            const { ipcRenderer } = require('electron');
            
            // 只保留一个主要的退出事件监听器
            ipcRenderer.once('app-before-quit', () => {
                this.cleanup();
                ipcRenderer.send('white-noise-cleanup-complete');
            });
            
            // 移除重复的 app-will-close 监听器，因为它和 app-before-quit 功能重复
            // ipcRenderer.on('app-will-close', () => {
            //     this.cleanup();
            // });
            
            // 应用失去/获得焦点的监听器
            ipcRenderer.on('app-blur', () => {
                this.isInBackground = true;
            });
            
            ipcRenderer.on('app-focus', () => {
                this.isInBackground = false;
            });
        }
        
        // 保留 beforeunload 作为备用清理机制，但使用 once 确保只执行一次
        window.addEventListener('beforeunload', () => {
            this.cleanup();
        }, { once: true });
        
        // 监听页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.isInBackground = true;
            } else {
                this.isInBackground = false;
            }
        });
    }
    
    toggleNoise(noiseKey) {
        const noise = this.noises[noiseKey];
        if (!noise) return;
        
        if (noise.isPlaying) {
            noise.audio.pause();
            noise.isPlaying = false;
        } else {
            noise.audio.play().catch(console.error);
            noise.isPlaying = true;
        }
        
        this.saveSettings();
    }
    
    setVolume(noiseKey, volume) {
        const noise = this.noises[noiseKey];
        if (!noise) return;
        
        noise.volume = Math.max(0, Math.min(1, volume));
        noise.audio.volume = noise.volume;
        this.saveSettings();
    }
    
    stopAll() {
        Object.keys(this.noises).forEach(key => {
            const noise = this.noises[key];
            if (noise.isPlaying) {
                noise.audio.pause();
                noise.isPlaying = false;
            }
        });
        this.saveSettings();
    }
    
    // 新增：清理所有音频资源
    // 修改 cleanup 方法，添加重复清理检查
    cleanup() {
        if (this.isCleanedUp) {
            console.log('白噪音资源已经清理过，跳过重复清理');
            return;
        }
        
        console.log('开始清理白噪音资源...');
        this.isCleanedUp = true;
        
        Object.keys(this.noises).forEach(key => {
            const noise = this.noises[key];
            if (noise.audio) {
                noise.audio.pause();
                noise.audio.currentTime = 0;
                noise.isPlaying = false;
                noise.audio.src = '';
                noise.audio.load();
            }
        });
        
        this.saveCleanupSettings();
        localStorage.setItem('whiteNoiseLastCleanup', Date.now().toString());
        
        console.log('白噪音资源清理完成');
    }
    
    // 新增：保存清理后的设置（只保存音量，清除播放状态）
    saveCleanupSettings() {
        const settings = {};
        Object.keys(this.noises).forEach(key => {
            const noise = this.noises[key];
            settings[key] = {
                volume: noise.volume,
                isPlaying: false // 强制设置为不播放
            };
        });
        localStorage.setItem('whiteNoiseSettings', JSON.stringify(settings));
    }
    
    saveSettings() {
        const settings = {};
        Object.keys(this.noises).forEach(key => {
            const noise = this.noises[key];
            settings[key] = {
                volume: noise.volume,
                isPlaying: noise.isPlaying
            };
        });
        localStorage.setItem('whiteNoiseSettings', JSON.stringify(settings));
    }
    
    loadSettings() {
        try {
            const settings = JSON.parse(localStorage.getItem('whiteNoiseSettings') || '{}');
            Object.keys(settings).forEach(key => {
                if (this.noises[key]) {
                    this.noises[key].volume = settings[key].volume || 0.5;
                    this.noises[key].audio.volume = this.noises[key].volume;
                    
                    // 修改：只有在用户主动操作时才恢复播放状态
                    // 应用启动时不自动播放，避免上次关闭时的声音继续播放
                    if (settings[key].isPlaying && this.shouldAutoResume()) {
                        // 延迟播放以避免自动播放限制
                        setTimeout(() => {
                            this.toggleNoise(key);
                        }, 1000);
                    }
                }
            });
        } catch (error) {
            console.warn('加载白噪音设置失败:', error);
        }
    }
    
    // 新增：判断是否应该自动恢复播放
    shouldAutoResume() {
        // 检查是否是应用重启后的首次加载
        const lastCleanup = localStorage.getItem('whiteNoiseLastCleanup');
        const now = Date.now();
        
        if (!lastCleanup) {
            // 首次使用，不自动播放
            return false;
        }
        
        const timeSinceCleanup = now - parseInt(lastCleanup);
        // 如果距离上次清理超过5分钟，认为是新的会话，不自动播放
        return timeSinceCleanup < 5 * 60 * 1000;
    }
    
    getNoiseList() {
        return Object.keys(this.noises).map(key => ({
            key,
            name: this.noises[key].name,
            volume: this.noises[key].volume,
            isPlaying: this.noises[key].isPlaying
        }));
    }
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = WhiteNoiseManager;
} else {
    window.WhiteNoiseManager = WhiteNoiseManager;
}